package com.ycsj.goldmedalnewconcept.teacher.activity;

import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.manager.BqaManager;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.PickerManager;
import com.ycsj.common.manager.SrfManager;
import com.ycsj.common.utils.DateUtils;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.ResultInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.StateCodeUtils;
import com.ycsj.goldmedalnewconcept.teacher.adapter.AttendanceRvAdapter;
import com.ycsj.goldmedalnewconcept.teacher.adapter.ClassGvAdapter;
import com.ycsj.goldmedalnewconcept.teacher.bean.AttenInfo;
import com.ycsj.goldmedalnewconcept.teacher.bean.ClassInfo;
import com.ycsj.goldmedalnewconcept.teacher.utils.ClassPoputil;
import com.ycsj.goldmedalnewconcept.teacher.utils.ClassUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 考勤管理
 * Created by Administrator on 2019/3/29 0029.
 */

public class TeacherAttendanceManagerActivity extends BaseActivity implements SrfManager.OnPullRefreshListener {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.lv_edit)
    ImageView lvEdit;
    @BindView(R.id.lv_class)
    ImageView lvClass;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.srf)
    SmartRefreshLayout srf;
    @BindView(R.id.bt_save)
    Button btSave;
    @BindView(R.id.rl_content)
    LinearLayout rlContent;
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;

    //所有班级的列表
    private List<ClassInfo.ListBean> classInfos;

    //展示班级列表的适配器
    private ClassGvAdapter classGvAdapter;

    //记录弹出展示班级列表PopUpWindow的选中位置的值,默认第一个被选中
    private int popSelectedPos = 0;

    //今天的日期,格式化yyyy-M-dd
    private String today;

    //记录选择的时间
    private String chooseDate;

    //考勤管理的数据
    private List<AttenInfo.ListBean> oldDatas;

    //记录的克隆数据,用于比对用户提交时是否修改了考勤信息
    private List<AttenInfo.ListBean> cloneDatas;

    //数据适配器
    private AttendanceRvAdapter adapter;

    //空视图和头布局
    private View emptyView, headView;

    //头布局的相关视图
    private ImageView ivChooseDate;
    private TextView tvDate;
    private TextView tvDetails;

    //请求的参数
    private String acc, role, apptoken;

    //时间格式
    private String patern = "yyyy-MM-dd";

    //推送的班级id
    private String classnum;

    //推送日期
    private String date;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_teacher_attendance_manager;
    }

    @Override
    protected void init() {
        initStateBar();

        //初始化下拉刷新
        initSrf();

        //模拟请求参数
        initParams();

        //请求班级数据
        httpClass();
    }


    /**
     * 模拟请求参数
     */
    private void initParams() {
        acc = AccountUtils.getAccount(this);
        role = AccountUtils.getRole(this);
        apptoken = AccountUtils.getToken(this);
        today = DateUtils.getTime(new Date(), patern);
        chooseDate = DateUtils.getTime(new Date(), patern);

        //时间
        date = getIntent().getStringExtra("date");
        if (TextUtils.isEmpty(date)) {
            chooseDate = DateUtils.getTime(new Date(), patern);
        } else {
            chooseDate = date;

        }

        //接收到的班级id
        classnum = getIntent().getStringExtra("classnum");
    }

    /**
     * 初始化下拉刷新
     */
    private void initSrf() {
        SrfManager.setSmartByPullListener(srf, this);
    }


    /**
     * 请求班级里列表数据
     */
    private void httpClass() {
        ClassUtil.httpClass(rlLoading, this, new ClassUtil.onSuccessListener() {
            @Override
            public void onSuccess(List<ClassInfo.ListBean> datas) {
                //回调班级数据
                classInfos = datas;

                //证明有班级
                lvEdit.setVisibility(View.VISIBLE);
                lvClass.setVisibility(View.VISIBLE);

                //设置数据
                initRv();

                //通知跳转同步班级选中状态
                initPos();

                //请求页面列表数据
                httpPageData(popSelectedPos, BqaManager.NORML);
            }

            @Override
            public void hasNoData() {
                //没有班级,不显示顶部的切换班级的按钮和
                lvEdit.setVisibility(View.INVISIBLE);
                lvClass.setVisibility(View.INVISIBLE);
            }
        });
    }

    /**
     * 初始化班级位置
     */
    private void initPos() {
        if (!TextUtils.isEmpty(classnum)) {
            for (int i = 0; i < classInfos.size(); i++) {
                if (classnum.equals(classInfos.get(i).getNum())) {
                    popSelectedPos = i;

                    break;
                }
            }
        }
    }

    /**
     * 初始化列表数据
     */
    private void initRv() {
        cloneDatas = new ArrayList<>();
        oldDatas = new ArrayList<>();
        headView = View.inflate(this, R.layout.teacher_headview_attendance, null);
        ivChooseDate = headView.findViewById(R.id.iv_choose_date);
        tvDate = headView.findViewById(R.id.tv_date);
        tvDetails = headView.findViewById(R.id.tv_details);
        ivChooseDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //选择日期
                chooseTimePicker();
            }
        });

        if (!TextUtils.isEmpty(date)) {
            tvDate.setText(date);
        }


        emptyView = View.inflate(this, R.layout.base_rv_common_empty_view, null);
        TextView tvMsg = emptyView.findViewById(R.id.tv_content);
        tvMsg.setText("该班级暂无考勤信息");
        adapter = new AttendanceRvAdapter(this, R.layout.teacher_rv_attendance_manager, oldDatas);
        adapter.addHeaderView(headView);
    }


    /**
     * 请求页面数据
     *
     * @param popSelectedPos 选中的班级位置
     * @param method         请求的方式
     */
    /**
     * 请求页面数据的方法
     *
     * @param popSelectedPos
     */
    private void httpPageData(int popSelectedPos, final int method) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "5");
        map.put("acc", acc);
        map.put("classnum", classInfos.get(popSelectedPos).getNum() + "");
        map.put("attendance_date", chooseDate);
        map.put("apptoken", apptoken);
        map.put("platform", "2");

        HttpUtils.post(HttpAddress.ATTENDANCEMANAGEMENT, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                BqaManager.setErrorNet(rlLoading, srf, method, adapter);
            }

            @Override
            public void onResponse(String response, int id) {
                if (rlLoading != null && rlLoading.getVisibility() == View.VISIBLE) {
                    rlLoading.setVisibility(View.GONE);
                }
                if (rlContent != null && rlContent.getVisibility() != View.VISIBLE) {
                    rlContent.setVisibility(View.VISIBLE);
                }

                if (!TextUtils.isEmpty(response)) {
                    AttenInfo info = null;

                    try {
                        info = GsonUtil.jsonToBean(response, AttenInfo.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info && "200".equals(info.getState())) {

                        //设置头部数据
                        setHeadViewData(info);

                        //返回成功,设置列表数据
                        List<AttenInfo.ListBean> newDatas = info.getList();

                        if (newDatas != null) {
                            //记录克隆数据,注意:不能直接AddAll方法
                            cloneDatas.clear();
                            for (int i = 0; i < newDatas.size(); i++) {
                                AttenInfo.ListBean listBean = new AttenInfo.ListBean();
                                listBean.setAttendanceType(newDatas.get(i).getAttendanceType());
                                listBean.setIcon(newDatas.get(i).getIcon());
                                listBean.setName(newDatas.get(i).getName());
                                listBean.setSttel(newDatas.get(i).getSttel());
                                cloneDatas.add(listBean);
                            }

                            //没有数据的情况
                            if (newDatas.size() == 0) {
                                //没有学生数据
                                btSave.setVisibility(View.INVISIBLE);
                                lvEdit.setVisibility(View.INVISIBLE);
                            } else {
                                btSave.setVisibility(View.VISIBLE);
                                lvEdit.setVisibility(View.VISIBLE);
                            }

                            if (method == BqaManager.NORML) {
                                oldDatas.clear();
                                oldDatas.addAll(newDatas);
                                BqaManager.setRv(emptyView, TeacherAttendanceManagerActivity.this, adapter, rv);
                            } else {
                                //更新数据
                                BqaManager.updateRvBySmf(method, srf, rv, oldDatas, newDatas, adapter);
                                adapter.setEnableLoadMore(false);
                            }
                        }
                    } else {
                        ToastUtils.showShort("返回器返回异常,错误码是:" + info.getState());
                        Log.i("test", "返回器返回异常,错误码是:" + info.getState());
                    }
                } else {
                    Log.i("test", "服务器返回数据为空");
                }
            }
        });
    }


    /**
     * 设置头部数据
     *
     * @param info
     */
    private void setHeadViewData(AttenInfo info) {
        //应到
        String total = info.getTotal_num();
        //迟到
        String late = info.getLate_num();
        //旷到
        String absent = info.getAbsent_num();
        //请假
        String leave = info.getLeave_num();
        //已到
        String aatenNum = info.getAtten_num();

//        if ("0".equals(info.getAbsent_num()) && "0".equals(info.getLate_num()) && "0".equals(info.getLeave_num()) && "0".equals(info.getAtten_num())) {
//            tvDetails.setText("");
//        } else {
        tvDetails.setVisibility(View.VISIBLE);
        tvDetails.setText("应到 " + total + " 人," + "实到 " + aatenNum + " 人,迟到 " +
                late + " 人,请假 " + leave + " 人,旷到 " + absent + " 人");
//        }
    }

    /**
     * 弹出选择日期的弹框
     */
    private void chooseTimePicker() {
        PickerManager.showPickerByYeaerAndMonthAndDayByLimit(this, new PickerManager.onSelectedListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                //记录选择的开始时间
                chooseDate = DateUtils.getTime(date, patern);
                if (chooseDate.equals(today)) {
                    tvDate.setText("今日考勤汇总");
                } else {
                    tvDate.setText(DateUtils.getTime(date, patern) + "\n考勤汇总");
                }

                //刷新适配器起数据
                httpPageData(popSelectedPos, BqaManager.PULLREFRESH);
            }
        });
    }

    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_back, R.id.lv_edit, R.id.lv_class, R.id.bt_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.lv_edit:
                //数据分析
                TeacherStudAnalyzeActivity.goActivity(this, classInfos.get(popSelectedPos).getNum() + "");
                break;
            case R.id.lv_class:
                //选择班级
                showClassPop();
                break;
            case R.id.bt_save:
                //修改考勤信息后保存
                doSaveAction();
                break;
        }
    }


    /**
     * 选择班级的弹框
     */
    private void showClassPop() {
        ClassPoputil.showClassPop(this, classInfos, popSelectedPos, llTitle, new ClassPoputil.onPopItemClickListener() {
            @Override
            public void onItemClick(int pos) {
                //记录当前点击条目的位置
                popSelectedPos = pos;

                //请求页面数据
                httpPageData(popSelectedPos, BqaManager.PULLREFRESH);
            }
        });
    }


    /**
     * 保存修改的考勤记录
     */
    private void doSaveAction() {
        if (hasUpdate()) {
            if (hasCompleteUpdate()) {
                //是否所有的学生都选择了考勤记录
                //修改过,进行上传
                CustomDialogManager.show(this, "保存中...");
                Map<String, String> map = new HashMap<>();
                map.put("type", "6");
                map.put("acc", acc);
                map.put("role", role);
                map.put("apptoken", apptoken);
                map.put("classnum", classInfos.get(popSelectedPos).getNum() + "");
                map.put("attendance_date", chooseDate);
                map.put("platform", "2");
                map.put("list", GsonUtil.listToJson(oldDatas));

                HttpUtils.post(HttpAddress.SAVAATTENDANCEMANAGEMENT, map, this, new HttpUtils.CallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        CustomDialogManager.dissmiss();
                        ToastUtils.showShort(BaseApplication.ERROR + ",保存失败");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        CustomDialogManager.dissmiss();
                        if (!TextUtils.isEmpty(response)) {
                            ResultInfo info = null;
                            try {
                                info = GsonUtil.jsonToBean(response, ResultInfo.class);
                            } catch (Exception e) {
                                Log.i("test", "数据解析异常");
                            }
                            if (null != info && "200".equals(info.getState())) {
                                //保存成功
                                ToastUtils.showShort("保存成功");
                                //关闭当前页面
                                finish();
                            } else {
                                StateCodeUtils.showSateCode(info.getState());
                                Log.i("test", "保存失败,错误码是:" + info.getState());
                            }
                        }
                    }
                });
            } else {
                ToastUtils.showShort("考勤记录未填写完整,请检查");
                return;
            }

        } else {
            //没有做过修改,不需要上传
            ToastUtils.showShort("未做任何修改,不需要保存");
            return;
        }
    }


    /**
     * 判断是否对考勤记录做过修改的方法
     */

    private boolean hasUpdate() {
        boolean res = false;
        for (int i = 0; i < oldDatas.size(); i++) {
            if (!oldDatas.get(i).getAttendanceType().equals(cloneDatas.get(i).getAttendanceType())) {
                res = true;
                break;
            }
        }
        return res;
    }


    /**
     * 判读是否所有学生都填写了考勤记录方法
     *
     * @return
     */
    private boolean hasCompleteUpdate() {
        boolean res = true;
        for (int i = 0; i < oldDatas.size(); i++) {
            if (TextUtils.isEmpty(oldDatas.get(i).getAttendanceType())) {
                res = false;
                break;
            }
        }
        return res;
    }

    /**
     * 下来刷新
     *
     * @param refreshlayout
     */
    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        //下拉刷新
        httpPageData(popSelectedPos, BqaManager.PULLREFRESH);
    }

    @Override
    protected void onDestroy() {
        if (null != adapter) {
            adapter.releaseHandler();
        }
        super.onDestroy();
    }
}
